-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.


-- Description: 框架Chip锁为续锁，通组件对同一个Chip二次加锁能成功，因此加锁时先要判断是否有锁，并且不能重入

local skynet = require 'skynet'
local singleton = require 'mc.singleton'

local UNLOCKED<const> = 0

local lock_chip = {}
lock_chip.__index = lock_chip

function lock_chip.new()
    return setmetatable({queue = skynet.queue()}, lock_chip)
end

function lock_chip:lock(chip, ctx, lock_time)
    return self.queue(function ()
        if not chip.SetLockStatus then
            return 0
        end
        if chip.LockStatus ~= UNLOCKED then
            return -1
        end
        return chip:SetLockStatus(ctx, 1, lock_time)
    end)
end

function lock_chip:unlock(chip, ctx)
    return self.queue(function ()
        if not chip.SetLockStatus then
            return 0
        end
        return chip:SetLockStatus(ctx, 0, 0)
    end)
end

return singleton(lock_chip)